package com.agile.leetcode.node.removeNthFromEnd;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/5 16:03
 */
public class RemoveNthFromEnd {
    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        RemoveNthFromEnd removeNthFromEnd = new RemoveNthFromEnd();
        ListNode node = removeNthFromEnd.removeNthFromEnd(node5, 1);
        System.out.println(node);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 拿到dummy节点
        ListNode dummy = new ListNode(0);
        // 拿到指针
        ListNode current = dummy;
        // 遍历
        while (head != null) {
            // 创建新的节点
            ListNode temp = new ListNode(head.val, head.next);
            // 遍历
            for (int i = 0; i < n; i++) {
                temp = temp.next;
            }
            if (temp == null) {
                // 找到了
                current.next = head.next;
                break;
            } else {
                current.next = head;
            }
            current = current.next;
            head = head.next;
        }
        return dummy.next;
    }
}

class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode() {
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
